#include <iostream>
#include<vector>
using namespace std;
 struct TreeNode 
 {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 };
 class Solution {
 public:
     TreeNode* _buildTree(const vector<int>& preorder, const vector<int>& inorder, int& pos, int left, int right)
     {
         if (left > right)
             return nullptr;
         TreeNode* head = new TreeNode(preorder[pos]);
         int mid = left;
         while (mid < right)
         {
             if (preorder[pos] == inorder[mid])
                 break;
             mid++;
         }
         pos++;
         head->left = _buildTree(preorder, inorder, pos, left, mid - 1);
         head->right = _buildTree(preorder, inorder, pos, mid + 1, right);
         return head;
     }
     TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
         int i = 0;
         return _buildTree(preorder, inorder, i, 0, inorder.size() - 1);
     }
 };
void preorder(TreeNode* root)
{
    if (!root)
    {
        cout << "null" << " ";
        return;
    }
    cout << root->val;
    cout << "->";
    preorder(root->left);
    preorder(root->right);
}
int main()
{
    vector<int> preorder1 = { 3,9,20,15,7 };
    vector<int> inorder = { 9,3,15,20,7 };
    TreeNode* root = Solution().buildTree(preorder1, inorder);
    preorder(root);
    return 0;
}